<template>
    <el-container style="height: 950px; border: 1px solid #eee">
        <!-- 左侧患者选择区 -->
        <el-aside width="350px">
            <el-container>
                <!-- 患者选择区头部 -->
                <el-header style="padding: 0;margin: 0">
                    <el-row>
                        <el-col :span="21" style="text-align: left">
                            <el-tag>患者选择：</el-tag>
                        </el-col>
                        <el-col :span="3" style="text-align: right">
                            <!-- 刷新按钮 -->
                            <el-button type="primary" size="small" @click="loadPatients" style="margin-right: 5px">
                                <el-icon><Refresh/></el-icon>
                            </el-button>
                        </el-col>
                    </el-row>
                    <el-row>
                        <!-- 患者搜索框 -->
                        <el-input placeholder="请输入内容" v-model="inputPatient" style="width: 100%">
                            <template #prepend>患者名：</template>
                            <template #append><el-icon><Search/></el-icon></template>
                        </el-input>
                    </el-row>
                </el-header>
                
                <!-- 患者列表主内容区 -->
                <el-main style="height: 800px;padding: 0;margin: 0">
                    <el-tabs type="border-card">
                        <!-- 本人患者标签页 -->
                        <el-tab-pane label="本人">
                            <!-- 未诊患者表格 -->
                            <el-tag size="small">未诊患者：</el-tag>
                            <el-table ref="singleTable" :data="filteredPatients01" highlight-current-row 
                                     @row-click="handleCurrentChange01" style="width: 100%;height: 50%" 
                                     :show-header="false" max-height="400" size="small">
                                <el-table-column property="caseNumber" label="病历号" width="80"/>
                                <el-table-column property="patientName" label="姓名"/>
                                <el-table-column property="age" label="年龄" width="50"/>
                            </el-table>
                            
                            <br/><br/>
                            
                            <!-- 已诊患者表格 -->
                            <el-tag size="small">已检验患者：</el-tag>
                            <el-table ref="singleTable" :data="filteredPatients02" @row-click="handleCurrentChange02"
                                     @row-dblclick="handleDBCurrentChange" style="width: 100%;height: 50%" 
                                     :show-header="false" size="small">
                                <el-table-column property="caseNumber" label="病历号" width="80"/>
                                <el-table-column property="patientName" label="姓名"/>
                                <el-table-column property="age" label="年龄" width="50"/>
                            </el-table>
                        </el-tab-pane>
                        
                        <!-- 科室患者标签页 -->
                        <el-tab-pane label="科室*">
                            <!-- 科室未诊患者表格 -->
                            <el-tag size="small">未诊患者：</el-tag>
                            <el-table ref="singleTable" :data="filteredDeptPatients01" highlight-current-row
                                     @row-click="handleCurrentChange01" style="width: 100%;height: 50%" 
                                     :show-header="false" size="small">
                                <el-table-column property="caseNumber" label="病历号" width="80"/>
                                <el-table-column property="patientName" label="姓名"/>
                                <el-table-column property="age" label="年龄" width="50"/>
                            </el-table>
                            
                            <!-- 科室已诊患者表格 -->
                            <el-tag size="small">已检验患者：</el-tag>
                            <el-table ref="singleTable" :data="filteredDeptPatients02" @row-click="handleCurrentChange02"
                                     @row-dblclick="handleDBCurrentChange" style="width: 100%;height: 50%" 
                                     :show-header="false" size="small">
                                <el-table-column property="caseNumber" label="病历号" width="80"/>
                                <el-table-column property="patientName" label="姓名"/>
                                <el-table-column property="age" label="年龄" width="50"/>
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </el-main>
            </el-container>
        </el-aside>
  
        <!-- 右侧主功能区 -->
        <el-container direction="vertical" style="height: 950px">
            <!-- 顶部患者信息展示区 -->
            <el-row>
                <span style="margin-left: 20px;font-size: small;">{{showPatientsTop}}</span>            
            </el-row>
  
            <!-- 主功能标签页 -->
            <el-tabs type="border-card" :before-leave="toTab">
                <!-- 病历首页标签页 -->
                <el-tab-pane label="病历首页">
                    <el-container v-loading="loading">
                        <!-- 病历表单 -->
                        <el-main style="width:100%;background:#fff;height:800px;overflow-y: auto">
                            <el-form ref="form" :model="medicalRecord01" label-width="80px" 
                                    label-position="left" size="small">
                                <!-- 操作按钮区：使用link替代text -->
                                <el-row style="background-color: #EAF1F5;margin-top: -20px">
                                    <el-col :span="8" style="margin-top: 4px;"></el-col>
                                    <el-col :span="4">
                                        <el-button type="link" size="small" @click="stageCheck">暂存</el-button>
                                    </el-col>
                                    <el-col :span="4">
                                        <el-button type="link" size="small" @click="saveCheck">提交</el-button>
                                    </el-col>
                                    <el-col :span="4">
                                        <el-button type="link" size="small" :disabled="isSaved" @click="cleanCheck">清空所有</el-button>
                                    </el-col>
                                    <el-col :span="4">
                                        <el-button type="link" size="small" @click="refMedicalRecord">刷新</el-button>
                                    </el-col>
                                </el-row>
                                
                                <!-- 病历内容表单 -->
                                <el-tag>病史内容：</el-tag>
                                <el-form-item label="主诉">
                                    <el-input type="textarea" :rows="1" v-model="medicalRecord01.chiefComplaint" :disabled="isSaved"/>
                                </el-form-item>
                                <el-form-item label="现病史">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.presentIllness" :disabled="isSaved"/>
                                </el-form-item>
                                <el-form-item label="现病治疗情况">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.presentTreatment" :disabled="isSaved"/>
                                </el-form-item>
                                <el-form-item label="既往史">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.history" :disabled="isSaved"/>
                                </el-form-item>
                                <el-form-item label="过敏史">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.allergy" :disabled="isSaved"/>
                                </el-form-item>
                                <el-form-item label="体格检查">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.physicalExam" :disabled="isSaved"/>
                                </el-form-item>
                                <el-form-item label="诊断">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.diagnosis" :disabled="isSaved"/>
                                </el-form-item>
                                <el-form-item label="检查建议">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.recommendation" :disabled="isSaved"/>
                                </el-form-item>
                                <el-form-item label="注意事项">
                                    <el-input type="textarea" :rows="2" v-model="medicalRecord01.precaution" :disabled="isSaved"/>
                                </el-form-item>
                            </el-form>
                            <el-button type="link" size="small" @click="saveCheck">提交</el-button>
                        </el-main>
                    </el-container>
                </el-tab-pane>
                
             <!-- 检验申请标签页 -->
<el-tab-pane label="检验申请*" :lazy="true">
  <div>
    <!-- 新增检验申请对话框 -->
    <el-dialog title="新增检验申请" v-model="dialog01Visible" width="50%">
      
      <el-form size="small" :model="examForm" ref="examFormRef" :rules="formRules">
        <!-- 检验科室选择 -->
        <el-form-item label="检验科室" prop="departmentId" required>
          <el-select 
            v-model="examForm.departmentId" 
            placeholder="请选择检验科室"
            @change="handleDeptChange"
            clearable
          >
            <el-option 
              v-for="dept in deptList" 
              :key="dept.id"
              :label="dept.name" 
              :value="dept.id"
            />
          </el-select>
        </el-form-item>

        <!-- 检验项目搜索 -->
        <el-form-item>
          <el-input 
            placeholder="搜索检验项目（名称或编码）" 
            v-model="itemSearchKey" 
            style="width: 100%"
            clearable
          >
            <template #append>
              <el-button :icon="Search" size="small" @click="filterItems"></el-button>
            </template>
          </el-input>
        </el-form-item>

        <!-- 修改为多选表格 -->
        <el-form-item label="检验项目" prop="selectedItems" required>
          <el-table 
            border 
            :data="filteredItems" 
            size="small"
            @selection-change="handleItemSelectionChange"
            max-height="300"
            ref="examTableRef"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column type="index" label="序号" width="50" />
            <el-table-column prop="code" label="项目编码" width="100" />
            <el-table-column prop="name" label="项目名称" />
            <el-table-column prop="specification" label="规格" width="150" />
            <el-table-column label="所属科室" width="120">
              <template #default="scope">
                {{ departmentMap.get(scope.row.departmentId) || '未知科室' }}
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价" width="80" />
          </el-table>
        </el-form-item>

        <!-- 显示已选项目 -->
        <el-form-item label="已选项目">
          <el-tag 
            v-for="item in selectedExamItems" 
            :key="item.id" 
            closable 
            @close="removeSelectedItem(item)"
          >
            {{ item.name }} - {{ item.price }}元
          </el-tag>
        </el-form-item>

        <el-form-item label="是否加急：">
          <el-switch 
            v-model="examForm.isUrgent" 
            active-color="#13ce66"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitExamApplication">确 定</el-button>
          <el-button @click="dialog01Visible = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    
    <el-aside style="width: 700px;height: 500px;">
      <!-- 操作按钮区 -->
      <el-row style="background-color: #EAF1F5">
        <el-col :span="8" style="margin-top: 4px;">
          <el-tag size="small">本项目金额合计：</el-tag>
          <el-tag type="warning" size="small">{{ totalPrice }}</el-tag>
        </el-col>
        <el-col :span="3">
          <el-button type="link" size="small" @click="dialog01Visible=true">新增项目</el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="link" size="small" @click="deleteSelectedItems">删除选择的检验项目</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="link" size="small" @click="confirmIssueItems">开立</el-button>
        </el-col>
      </el-row>

      <!-- 检验项目表格 -->
      <el-table 
        ref="examTableRef"
        :data="examinationList" 
        style="width: 100%;margin: 0px;padding: 0px;" 
        :show-header="true"
        border  
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50"/>
        <el-table-column property="itemName" label="项目名称" width="120"/>
     
        <el-table-column property="isUrgent" label="是否加急" width="80">
          <template #default="scope">
            {{ scope.row.isUrgent === 1 ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column property="departmentId" label="部门id" width="80"/>
        <el-table-column property="price" label="单价" width="80"/>
       
        <el-table-column property="createTime" label="申请时间" width="160"/>
      
      </el-table>

      <!-- 目的要求表单 -->
      <el-form ref="purposeFormRef" label-width="80px" style="margin-top: 20px;">
        <el-row>
          <el-col :span="24">
            <el-form-item label="目的要求">
              <el-input 
                type="textarea" 
                :rows="4" 
                placeholder="【检验目的：】【患者主诉：】【现病史：】"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-aside>
  </div>
</el-tab-pane>

<!-- 新增“门诊确诊”标签页 -->
<el-tab-pane label="门诊确诊">
  <el-container v-loading="loading">
    <el-main style="width:100%;background:#fff;height:800px;overflow-y: auto">
      <el-form ref="confirmFormRef" :model="confirmForm" label-width="80px" 
               label-position="left" size="small">
        <!-- 操作按钮区 -->
        <el-row style="background-color: #EAF1F5;margin-top: -20px">
          <el-col :span="8" style="margin-top: 4px;"></el-col>
          <el-col :span="4">
            <el-button type="link" size="small" @click="saveConfirmed">保存</el-button>
          </el-col>
        </el-row>

        <!-- 患者信息展示与编辑 -->
        <el-tag>患者基本信息：</el-tag>
        <el-form-item label="病历号">
          <el-input v-model="confirmForm.caseNumber" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="患者姓名">
          <el-input v-model="confirmForm.patientName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="confirmForm.gender" placeholder="请选择性别" @change="handleGenderChange">
            <el-option label="男" value="71"></el-option>
            <el-option label="女" value="72"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="confirmForm.age"></el-input>
        </el-form-item>

        <el-tag>诊断与检查信息：</el-tag>
        <el-form-item label="检查结果">
          <el-input type="textarea" :rows="3" v-model="confirmForm.inspectionResult"></el-input>
        </el-form-item>
        <el-form-item label="诊断结果">
          <el-input type="textarea" :rows="3" v-model="confirmForm.diagnosisResult"></el-input>
        </el-form-item>
        <el-form-item label="处理意见">
          <el-input type="textarea" :rows="3" v-model="confirmForm.treatmentOpinion"></el-input>
        </el-form-item>
      </el-form>
    </el-main>
  </el-container>
</el-tab-pane>
</el-tabs>
        </el-container>
    </el-container>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import { ElMessage, ElNotification, ElMessageBox } from 'element-plus'
import service from '@/utils/request'
import { Search, Refresh } from "@element-plus/icons-vue"
import { useUserStore } from '@/stores/counter'
// 在script中添加
const confirmFormRef = ref(null);
// 获取用户store
const userStore = useUserStore()
// 新增：门诊确诊表单数据
const confirmForm = ref({
  caseNumber: '',
  patientName: '',
  gender: '',
  age: '',
  inspectionResult: '',
  diagnosisResult: '',
  treatmentOpinion: ''
})
// 修正后代码
function loadConfirmForm(patient) {
  // 确保patient存在
  if (!patient) {
    console.error('未获取到患者数据');
    return;
  }
  
  confirmForm.value = {
    caseNumber: patient.caseNumber || '',
    patientName: patient.patientName || '',
    gender: patient.gender === 71 ? 71 : 72, // 保持数字类型，与选择器value一致
    age: patient.age || '',
    inspectionResult: '',
    diagnosisResult: '',
    treatmentOpinion: ''
  };
  
  // 将日志移到函数内部，确保选中患者时才执行
  console.log('加载患者到确诊表单:', confirmForm.value);
}
async function saveConfirmed() {
  if (!currentRegistrationId.value) {
    ElMessage.warning('请先选择患者');
    return;
  }

  try {
    // 1. 调用接口更新患者 visitStatus 为 4
    await service.post('/registration/updateStatus', {
      id: currentRegistrationId.value,
      visitStatus: 4
    })

   

    ElMessage.success('保存成功，患者状态已更新为“门诊确诊”');
    // 3. 刷新患者列表（可选，根据需求决定是否重新拉取数据）
    loadPatients();
  } catch (error) {
    ElMessage.error('保存失败，请重试');
    console.error('保存门诊确诊信息失败:', error);
  }
}
// 响应式数据定义
const inputPatient = ref('') // 搜索输入
const loading = ref(false) // 全局加载状态
const loadingPatients = ref(false) // 患者列表加载状态
const currentRegistrationId = ref(null) // 当前患者的 registrationId
const examinationList = ref([]) // 检验申请列表
const selectedExamItems = computed(() => {
    return examForm.value?.selectedItems || []
})
// 患者列表数据
const RegistersTable01 = ref([]) // 本人未诊患者
const RegistersTable02 = ref([]) // 本人已诊患者
const MyPatientsData01 = ref([]) // 科室未诊患者
const MyPatientsData02 = ref([]) // 科室已诊患者

// 检验申请相关数据
const dialog01Visible = ref(false)
const examFormRef = ref(null)
const itemSearchKey = ref('')
const deptList = ref([]) // 检验科室列表
const allMedicalItems = ref([]) // 所有检验项目
const filteredItems = ref([]) // 过滤后的检验项目
const departmentMap = new Map() // 科室ID到名称的映射表
const examTableRef = ref(null)

const examForm = ref({
    departmentId: null,  // 执行科室ID
    isUrgent: 0,         // 是否加急：0-否，1-是
    registrationId: null, // 患者挂号ID
    items: [],           // 选中的检验项目列表
    selectedItems: []    // 选中的项目（用于表单验证）
})

const selectedRows = ref([]) // 用于检验项目表格的多选

// 表单验证规则
const formRules = ref({
    departmentId: [
        { required: true, message: '请选择检验科室', trigger: 'change' }
    ],
    selectedItems: [
        { required: true, message: '请至少选择一个检验项目', trigger: 'change' }
    ]
})

// 其他状态变量
const currentPatient = ref(null)
const showPatientsTop = ref("请选择患者")
const showStop = ref(false)
const isSaved = ref(false)
const tableData02 = ref([])
const selectData01 = ref([])
const switch01 = ref(false)
const msg01 = ref('')

// 加载检验科室列表
async function loadDepartments() {
    try {
        // 直接使用响应数据，已在拦截器中处理
        const res = await service.get('/dept/list')
        const allDepts = res || []
        deptList.value = allDepts.filter(dept => dept.type === 2);
        // 构建科室ID到名称的映射
        deptList.value.forEach(dept => {
            departmentMap.set(dept.id, dept.name)
        })
    } catch (error) {
        ElMessage.error('获取检验科室失败')
        console.error(error)
    }
}

// 加载所有检验项目
async function loadAllMedicalItems() {
    try {
        // 直接使用响应数据
        const res = await service.get('/medicalItem/getAll')
        allMedicalItems.value = res || []
        console.log(res)
        filteredItems.value = [...allMedicalItems.value]
    } catch (error) {
        ElMessage.error('获取检验项目失败')
        console.error(error)
    }
}

// 科室切换时过滤项目
function handleDeptChange() {
    // 清空项目选择
    clearSelectedItems()
    
    // 按科室过滤项目
    if (examForm.value.departmentId) {
        filteredItems.value = allMedicalItems.value.filter(
            item => item.departmentId === examForm.value.departmentId
        )
    } else {
        filteredItems.value = [...allMedicalItems.value]
    }
}

// 搜索过滤项目
function filterItems() {
    if (!itemSearchKey.value) {
        handleDeptChange() // 无搜索词时按科室过滤
        return
    }
    
    const key = itemSearchKey.value.toLowerCase()
    filteredItems.value = allMedicalItems.value
        .filter(item => !examForm.value.departmentId || item.departmentId === examForm.value.departmentId)
        .filter(item => 
            item.name.toLowerCase().includes(key) || 
            item.code.toLowerCase().includes(key)
        )
}

// 更新表单中的项目列表
function updateExamFormItems() {
    examForm.value.items = examForm.value.selectedItems.map(item => ({
        itemId: item.id,
        itemName: item.name,
        price: item.price,
        departmentId: item.departmentId
    }))
}
function handleItemSelectionChange(rows) {
    examForm.value.selectedItems = rows || [];
    console.log("选中的项目：", examForm.value.selectedItems); // 测试是否有值
    updateExamFormItems();
}
// 移除选中的项目
function removeSelectedItem(item) {
    const index = examForm.value.selectedItems.findIndex(i => i.id === item.id)
    if (index !== -1) {
        examForm.value.selectedItems.splice(index, 1)
        updateExamFormItems()
        
        // 取消表格中的选中状态
        if (examTableRef.value) {
            examTableRef.value.toggleRowSelection(item, false)
        }
    }
}
// 替换原有的 totalPrice 计算逻辑
const totalPrice = computed(() => {
    // 从实际展示的检验列表中计算总金额
    const sum = examinationList.value.reduce((acc, item) => {
        // 确保 price 是数字（避免 undefined 或字符串导致计算错误）
        return acc + Number(item.price || 0);
    }, 0);
    return sum.toFixed(2) + '元';
});
// 清空选中项目
function clearSelectedItems() {
    examForm.value.selectedItems = []
    updateExamFormItems()
    
    // 取消表格中的所有选中状态
    if (examTableRef.value) {
        examTableRef.value.clearSelection()
    }
}

// 选择检验项目
function selectMedicalItem(row) {
    examForm.value.medicalItemId = row.id
    examForm.value.itemName = row.name
    examForm.value.price = row.price
    examForm.value.departmentId = row.departmentId // 确保科室一致
}

// 提交检验申请（修改为提交多个项目）
async function submitExamApplication() {
    updateExamFormItems()
    // 表单验证
    const valid = await examFormRef.value.validate()
    if (!valid) return
    if (!currentRegistrationId.value) {
        ElMessage.error('未获取到患者挂号信息，请重新选择患者');
        return; // 终止提交
    }
    
    const batchData = examForm.value.items.map(item => ({
        ...item,
        registrationId: currentRegistrationId.value, // 关联患者挂号ID
        isUrgent: examForm.value.isUrgent, // 同步加急状态
        medicalRecordId: medicalRecord01.value.id
    }))
    console.log('最终提交的检验申请数据:', batchData);
    try {
        // 批量提交多个检验项目
        const res = await service.post('/examApp/saveBatch', batchData)
        ElMessage.success('检验申请添加成功')
        dialog01Visible.value = false
        // 刷新检验列表
        loadExaminationList()
        // 重置表单
        clearSelectedItems()
        examFormRef.value.resetFields()
        itemSearchKey.value = ''
    } catch (error) {
        ElMessage.error('添加检验申请失败')
        console.error('保存错误:', error)
        console.log("错误类型:", typeof error)
        console.log("错误详情:", error) 
        console.log("响应数据:", error.response?.data) // 后端返回的错误信息
        ElMessage.error('添加检验申请失败')
    }
}
// 新增检验申请按钮点击事件（需在模板中绑定）
function openExamDialog() {
    if (!medicalRecord01.value?.id) {
        // 病历未保存时，提示并引导保存
        ElMessageBox.confirm(
            '未找到患者病历，是否先保存病历？',
            '提示',
            {
                confirmButtonText: '去保存',
                cancelButtonText: '取消',
                type: 'warning'
            }
        ).then(() => {
            // 切换到“病历首页”标签页，方便用户保存
            const tabs = document.querySelector('.el-tabs__nav');
            if (tabs) {
                tabs.children[0].click(); // 点击第一个标签页（病历首页）
            }
        }).catch(() => {
            // 取消操作，不打开对话框
        });
    } else {
        // 病历已保存，正常打开对话框
        dialog01Visible.value = true;
    }
}
// 过滤后的患者列表
const filteredPatients01 = computed(() => {
    return RegistersTable01.value.filter(patient => 
        patient.patientName?.includes(inputPatient.value) || 
        patient.caseNumber?.includes(inputPatient.value))
})
const filteredPatients02 = computed(() => {
    return RegistersTable02.value.filter(patient => 
        patient.patientName?.includes(inputPatient.value) || 
        patient.caseNumber?.includes(inputPatient.value))
})
const filteredDeptPatients01 = computed(() => {
    return MyPatientsData01.value.filter(patient => 
        patient.patientName?.includes(inputPatient.value) || 
        patient.caseNumber?.includes(inputPatient.value))
})
const filteredDeptPatients02 = computed(() => {
    return MyPatientsData02.value.filter(patient => 
        patient.patientName?.includes(inputPatient.value) || 
        patient.caseNumber?.includes(inputPatient.value))
})

// 加载检验申请列表
async function loadExaminationList() {
    if (!currentRegistrationId.value) return
    try {
        // 直接使用响应数据
        const res = await service.get('/examApp/list', {
            params: { registrationId: currentRegistrationId.value }
        })
        
        // 字段映射
        examinationList.value = (res || []).map(item => ({
            id: item.id,
            itemName: item.itemName,
            bodyPart: item.bodyPart,
            isUrgent: item.isUrgent,
            departmentId: item.departmentId,
            price: item.price,
            status: item.status,
            createTime: formatDate(item.createTime),
            result: item.result
        }))
    } catch (error) {
        ElMessage.error('获取检验申请列表失败')
    }
}

// 日期格式化工具函数
function formatDate(date) {
    if (!date) return ''
    return new Date(date).toLocaleString()
}

// 加载患者数据
async function loadPatients() {
    if (!userStore.isAuthenticated) {
        ElMessage.warning('请先登录')
        return
    }

    loadingPatients.value = true
    try {
        // 直接使用响应数据
        const undoneRes = await service.get('/registration/getByDoctorId', {
            params: { doctorId: userStore.id, visitStatus: 1 }
        })
        const doneRes = await service.get('/registration/getByDoctorId', {
            params: { doctorId: userStore.id, visitStatus: 3 }
        })
        const deptUndoneRes = await service.get('/registration/getByDept', {
            params: { deptId: userStore.departmentId, visitStatus: 1 }
        })
        const deptDoneRes = await service.get('/registration/getByDept', {
            params: { deptId: userStore.departmentId, visitStatus: 3 }
        })

        // 数据赋值
        RegistersTable01.value = Array.isArray(undoneRes) ? undoneRes : []
        RegistersTable02.value = Array.isArray(doneRes) ? doneRes : []
        MyPatientsData01.value = Array.isArray(deptUndoneRes) ? deptUndoneRes : []
        MyPatientsData02.value = Array.isArray(deptDoneRes) ? deptDoneRes : []

    } catch (error) {
        ElMessage.error('获取患者列表失败')
        console.error('加载患者错误:', error)
        // 错误时清空列表
        RegistersTable01.value = []
        RegistersTable02.value = []
        MyPatientsData01.value = []
        MyPatientsData02.value = []
    } finally {
        loadingPatients.value = false
    }
}

// 刷新患者列表
const reloadUser = loadPatients

// 选中患者（未诊）
function handleCurrentChange01(patient) {
    currentPatient.value = patient
    showPatientsTop.value = `${patient.patientName} (${patient.caseNumber}) - ${patient.gender === 71 ? '男' : '女'} ${patient.age}${patient.ageType || '岁'}`
    showStop.value = true
    loadMedicalRecord(patient.id)
    currentRegistrationId.value = patient.id // 记录 registrationId
    loadExaminationList() // 加载检验申请列表
    loadConfirmForm(patient);
}

// 选中患者（已诊）
function handleCurrentChange02(patient) {
    currentPatient.value = patient
    showPatientsTop.value = `${patient.patientName} (${patient.caseNumber}) - ${patient.gender === 71 ? '男' : '女'} ${patient.age}${patient.ageType || '岁'}`
    showStop.value = false
    loadMedicalRecord(patient.id)
    currentRegistrationId.value = patient.id // 记录 registrationId
    loadExaminationList() // 加载检验申请列表
    loadConfirmForm(patient);
}

// 加载患者病历
async function loadMedicalRecord(registrationId) {
    try {
        loading.value = true
        // 直接使用响应数据
        const medicalRecord = await service.get('/medicalRecord/getByRegistrationId', {
            params: { registrationId }
        })
        medicalRecord01.value = medicalRecord || {}
        isSaved.value = [2, 3].includes(medicalRecord01.value.status)
    } catch (error) {
        ElMessage.error('加载病历失败')
        console.error('病历加载错误:', error)
        medicalRecord01.value = {}
    } finally {
        loading.value = false
    }
}

// 双击查看病历
function handleDBCurrentChange(patient) {
    console.log('查看完整病历:', patient)
    ElNotification.info({
        title: '病历详情',
        message: `患者 ${patient.patientName} 的完整病历`
    })
}

// 诊毕操作
async function endRegister() {
    if (!currentPatient.value) return

    try {
        loading.value = true
        // 直接使用响应数据
        await service.post('/registration/updateStatus', {
            id: currentPatient.value.id,
            visitStatus: 3
        })
        ElMessage.success('诊毕操作成功')
        showStop.value = false
        loadPatients()
    } catch (error) {
        ElMessage.error('诊毕操作失败')
        console.error('诊毕错误:', error)
    } finally {
        loading.value = false
    }
}

// 清空病历表单
function cleanCheck() {
    medicalRecord01.value = {
        registrationId: currentPatient.value?.id,
        caseNumber: currentPatient.value?.caseNumber,
        status: 1
    }
    isSaved.value = false
}

// 刷新病历
const refMedicalRecord = () => {
    if (currentPatient.value) {
        loadMedicalRecord(currentPatient.value.id)
    }
}

// 标签页切换前验证
function toTab(activeTab, oldTab) {
    if (oldTab === '病历首页' && !isSaved.value) {
        return ElMessageBox.confirm(
            '当前病历未保存，确定切换标签页吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        ).then(() => true).catch(() => false)
    }
    return true
}

// 处理表格选择变化
function handleSelectionChange(rows) {
    selectedRows.value = rows
}

// 删除选中的检验项目
async function deleteSelectedItems() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的项目');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个检验项目吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const ids = selectedRows.value.map(item => item.id);
    
    // 直接发送ID数组，而非包含ids属性的对象
    await service.post('/examApp/deleteBatch', ids, {
      headers: {
        'Content-Type': 'application/json'
      }
    });

    ElMessage.success('删除成功');
    loadExaminationList();
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除');
      return;
    }

    const errorMessage = error.response?.data?.message || '删除失败，请重试';
    ElMessage.error(errorMessage);
    console.error('Error deleting items:', error);
  }
}

// 开立检验项目
function confirmIssueItems() {
    if (examinationList.value.length === 0) {
        ElMessage.warning('请先添加检验项目')
        return
    }
    
    ElMessageBox.confirm(
        '确定要开立选中的检验项目吗？',
        '确认开立',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
        }
    ).then(async () => {
        try {
            // 修改：将参数作为查询字符串传递，而不是请求体
            await service.post(`/examApp/updateStatus?registrationId=${currentRegistrationId.value}&status=1`);
            
            ElMessage.success('开立成功');
            loadExaminationList(); // 刷新列表
        } catch (error) {
            ElMessage.error('开立失败');
            console.error('Error updating status:', error);
        }
    }).catch(() => {
        ElMessage.info('已取消开立');
    });
}

// 暂存病历
function stageCheck() {
    ElMessage.success('暂存成功')
    // 实际项目中添加暂存接口调用
}
// 在响应式数据定义处补充默认结构
const medicalRecord01 = ref({
  registrationId: null, // 关联的患者挂号ID（必填）
  caseNumber: '',       // 病历号
  chiefComplaint: '',   // 主诉
  presentIllness: '',   // 现病史
  presentTreatment: '', // 现病治疗情况
  history: '',          // 既往史
  allergy: '',          // 过敏史
  physicalExam: '',     // 体格检查
  diagnosis: '',        // 诊断
  recommendation: '',   // 检查建议
  precaution: '',       // 注意事项
  status: 1             // 状态：1-暂存，2-提交（根据后端定义调整）
})
// 提交病历
async function saveCheck() {
  // 1. 校验患者是否已选择
  if (!currentRegistrationId.value) {
    ElMessage.warning('请先选择患者');
    return;
  }

  // 2. 校验核心必填字段（根据实际业务调整）
  if (!medicalRecord01.value.chiefComplaint) {
    ElMessage.warning('请填写主诉');
    return;
  }
 

  try {
    loading.value = true; // 显示加载状态

    // 3. 补充关联ID（关键：关联当前患者的挂号ID）
    medicalRecord01.value.registrationId = currentRegistrationId.value;
    medicalRecord01.value.caseNumber = currentPatient.value?.caseNumber; // 关联病历号
    medicalRecord01.value.status = 2; // 标记为“已提交”状态（与后端协商）

    // 4. 调用后端接口提交
    const response = await service.post('/medicalRecord/add', medicalRecord01.value);

    // 5. 处理成功响应
  
      ElMessage.success('病历提交成功');
      isSaved.value = true; // 标记为已保存状态
      // 6. 更新患者挂号状态（可选：如改为“已诊”）
      await updatePatientStatus();
    
  } finally {
    loading.value = false; // 关闭加载状态
  }
}

// 页面挂载时加载数据
onMounted(() => {
    loadPatients()
    loadDepartments() // 加载科室列表
    loadAllMedicalItems() // 加载检验项目
})
</script>